//
//  ProjectListNetWork.swift
//  mggz
//
//  Created by 匀视网Mac on 2018/1/8.
//  Copyright © 2018年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import Alamofire
import ObjectMapper



class  LCProjectListModel : Mappable{
    enum PjectStatus:Int {
        case 未立项 = 0,已立项,已中标,已验收,已完结, 已过保
    }
    var IsAppSelected: Bool = false //app端是否被选中
    var ProjectStatus: PjectStatus?//项目状态。如果大于等于2，则显示『已验收』，不用再判断下面4个字段。否则根据下面4个字段显示对应的内容
    var MarketSupplyBaseID : String?
    var MarketDemandBaseID : String?
    var OrderNo : String?
    var ProjectID : String?
    var ProjectName : String?
    var CompanyID : String?
    var OnGuardCount : Int?
    var OnLineCount : Int?
    var DutyRate : String?
    var Longitude : NSString?
    var Latitude : NSString?
    var SignedRange : Double?
    var ProjectRangeBean:ProjectRangeBean?
    
    
    required init?(map: Map) {
        
    }
    
    func mapping(map: Map) {
        IsAppSelected       <- map["IsAppSelected"]
        ProjectStatus       <- map["ProjectStatus"]
        MarketDemandBaseID       <- map["MarketDemandBaseID"]
        MarketSupplyBaseID       <- map["MarketSupplyBaseID"]
        OrderNo       <- map["OrderNo"]
        ProjectID       <- map["ProjectID"]
        ProjectName       <- map["ProjectName"]
        CompanyID       <- map["CompanyID"]
        OnGuardCount       <- map["OnGuardCount"]
        OnLineCount       <- map["OnLineCount"]
        DutyRate       <- map["DutyRate"]
        Longitude       <- map["Longitude"]
        Latitude       <- map["Latitude"]
        SignedRange       <- map["SignedRange"]
        ProjectRangeBean  <- map["ProjectRange"]
    }
}

class ProjectRangeBean:Mappable{
    var ElectricFenceList:[PointListBean]?
    var SignedPointList:[PointListBean]?
    
    required init?(map: Map) {
        
    }
    func mapping(map: Map) {
        ElectricFenceList   <- map["ElectricFenceList"]
        SignedPointList   <- map["SignedPointList"]
    }
    
}

class PointListBean:Mappable{
    var Latitude:String?
    var Longitude:String?
    var Order:Double?
    
    required init?(map: Map) {
        
    }
    
    func mapping(map: Map) {
        Latitude       <- map["Latitude"]
        Longitude       <- map["Longitude"]
        Order       <- map["Order"]
    }
}





class ProjectListNetWork: NSObject {
    enum ProjectStatus:Int {
        case 未立项 = 0,已立项,已中标,已验收,已完结, 已过保
    }
    
    var isAppSelected: Bool = false //app端是否被选中
    
    var projectStatus: ProjectStatus?//项目状态。如果大于等于2，则显示『已验收』，不用再判断下面4个字段。否则根据下面4个字段显示对应的内容
    var isWorking: Bool = false //是否在职
    var isApply: Bool = false   //是否申请中
    var isSupplyApply: Bool = false //提供申请
    var isLeaved: Bool = false  //是否离职，true表示离职
    
    
    
    var projectName: String?
    var companyName: String?
    var address: String?
    var demandBaseMigrantWorkerID: String?  //劳务包民工ID（一条项目有一个id，所以民工接了多个项目，每个项目都有对应的一条id）
    var migrantWorkerId: String? //民工ID（对于所有项目都是这个ID）
    var marketSupplyBaseID: String? //根据这个获取签到策略
    var businessChangerID: String? //业务负责人ID
    var orderNo: String? //发包编号
    var workHours: String?  //每日工作时长
    var daySalary:String? //每日工资
    
    
    required init(rootDict: [String: Any] ) {
        super.init()
        if let isAppSelected = rootDict["IsAppSelected"] as? Bool {
            self.isAppSelected = isAppSelected
            
        }
        
        self.marketSupplyBaseID = rootDict["MarketSupplyBaseID"] as? String
        self.demandBaseMigrantWorkerID = rootDict["DemandBaseMigrantWorkerID"] as? String
        self.migrantWorkerId = rootDict["MigrantWorkerID"] as? String
        self.projectName = rootDict["ProjectName"] as? String
        self.companyName = rootDict["CompanyName"] as? String
        self.address = rootDict["Address"] as? String
        self.businessChangerID = rootDict["BusinessChangerID"] as? String
        self.orderNo = rootDict["OrderNo"] as? String
        
        if let daySalary = rootDict["DaySalary"] as? Double {
            self.daySalary = String(format: "%0.2f", daySalary)
            
        }
        
        if let workHours = rootDict["WorkHours"] as? Double {
            self.workHours = String(format: "%0.2f", workHours)
        }
        
        if let projectStatus = rootDict["ProjectState"] as? Int {
            let aStatus = ProjectStatus.init(rawValue: projectStatus)
            self.projectStatus = aStatus
        }
        
        if let isWorking = rootDict["IsWorking"] as? Bool {
            self.isWorking = isWorking
        }
        
        if let isApplye = rootDict["IsApplying"] as? Bool {
            self.isApply = isApplye
        }
        
        if let isLeaved = rootDict["IsLeaved"] as? Bool {
            self.isLeaved = isLeaved
        }
        
        if self.isWorking == false && self.isApply == false && self.isLeaved == false {
            self.isSupplyApply = true
        }
        
    }
}














extension ProjectListNetWork {
    
    /// 获取项目列表
    ///
    /// 如果列表中有选中的项目，默认是第一条
    ///
    /// - Parameters:
    ///   - pageIndex: 页数，默认1是第一页
    ///   - pageSize: 一页的项目条数，默认25
    ///   - keyword: 用来搜索keyword关键字的项目列表，默认为空
    ///   - isShowApplying: 『调入申请』类型的项目是否也传回来，false表示不要传回来
    ///   - completionHandler: 返回后去的条目数组集合
    class func projectList(pageIndex:Int, pageSize: Int = 25 ,keyword: String = "",isShowApplying: Bool = false,completionHandler:@escaping (WWValueResponse<[LCProjectListModel]>) -> Void) {
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
        let httpHeaderDe = WWUser.sharedInstance.mobile_cilent_headers
        print("令牌:\(httpHeaderDe!)")
        let accountIdFt = WWUser.sharedInstance.accountId
        print("编码:\(accountIdFt!)")
        guard let httpHeader = WWUser.sharedInstance.mobile_cilent_headers else{
            
            return
        }
        
        let method = "MarTian.MigrantWorkerManage.Handler.AjaxMarketDemandBase.GetMarketDemandBase"
        let params = ["Method": method,"PageIndex":"\(pageIndex)","PageSize": "\(pageSize)", "AccountId":accountId, "IsShowFinish": "\(isShowApplying)"]
        Alamofire.request(API_CALL_METHOD, method: .post, parameters: params, headers: httpHeader).responseJSON { (response) in
            if response.result.isSuccess {
                print(response.result.value!)
                if let dict = response.result.value as? [String: AnyObject] {
                    
                    let status = LCStateStruct(rootJson: dict)
                    if status.success {
                        if let resultDic = dict["Result"] as? [String: AnyObject] {
                            if let itemDic = resultDic["Items"] as? [[String: Any]] {
                                var callbackArr = [LCProjectListModel]()
                                callbackArr = Mapper<LCProjectListModel>().mapArray(JSONArray: itemDic)
                                completionHandler(WWValueResponse.init(value: callbackArr, success: true))
                                return
                            }
                        }
                    }
                    completionHandler(WWValueResponse.init(success: false, message: "数据解析错误"))
                }
            }
            else {
                print("失败")
                completionHandler(WWValueResponse.init(success: false, message: "网络错误"))
            }
        }
    }
    
    //    根据DemandBaseMigrantWorkerID获取对应的项目
    class func updateSeletedState(_ MarketSupplyBaseID: String,completionHandler:@escaping (_ state:Bool) -> Void) {
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
        guard let httpHeader = WWUser.sharedInstance.mobile_cilent_headers else{
            return
        }
        let method = "MarTian.MigrantWorkerManage.Handler.AjaxMarketDemandBase.SetSupplyBaseSelectState"
        let params = ["Method":method, "MarketSupplyBaseID":MarketSupplyBaseID, "AccountId": accountId]
        Alamofire.request(API_CALL_METHOD, method: .post, parameters: params, headers: httpHeader).responseJSON { (response) in
            if response.result.isSuccess {
                if let dict = response.result.value as? [String: Any] {
                    print(dict)
                    let status = dict["State"] as? String
                    if status == "OK" {
                        completionHandler(true)
                        return
                    }
                    if status == "ERROR" {
                        completionHandler(false)
                        return
                    }
                
                }
                completionHandler(false)
            }
            else {
                print("网络访问错误")
                completionHandler(false)
            }
        }
        
    }
    
    
    class func updateProjectInformation(workerId: String, completionHandler: @escaping (WWResponse) -> Void) {
        let url = JsonAPIURL + "CallMethod"
        let method = "MarTian.MigrantWorkerManage.Handler.AjaxDemandBaseMigrantWorker.SetDemandBaseSelectState"
        let workerId = workerId
        guard let userModel = WWUser.sharedInstance.userModel, let accountId = userModel.accountId else {
            print("accountId为空")
            return
        }
        let params = ["Method": method, "DemandBaseMigrantWorkerID": workerId, "AccountId": accountId]
        let headerDic = ["Authorization": "Bearer" + " " + WWUser.sharedInstance.token!]
        Alamofire.request(url, method: .post, parameters: params, headers: headerDic).responseJSON { (response) in
            if response.result.isSuccess {
                let dic = response.result.value as! [String: AnyObject]
                let status = StatusStruct(rootJson: dic)
                completionHandler(WWResponse.init(success: status.success, message: status.statusString))
            }
            else {
                print("失败")
                completionHandler(WWResponse.init(success: false, message: "网络错误"))
            }
        }
    }
    
    
    //调入项目
    class func callInProject(_ guid: String, marketSupplyBaseID: String, businessChangerID: String, migrantWorkerID: String, orderNo: String,orderConfigId: String,completionHandler: @escaping (WWResponse) -> Void) {
        guard let httpHeader = mobile_cilent_headers() else{
            return
        }
        guard let userModel = WWUser.sharedInstance.userModel, let accountId = userModel.accountId else {
            print("accountId为空")
            return
        }
        let method = "KouFine.Handler.Core.AjaxOperate.SubmitProcess"
        let pageName = "KouFine.Container.Form"
        let approvalNote = "提交审批"
        let carbonList = ""
        
        let businessChanger = ["ID":businessChangerID]
        let companyCharger = ["BusinessChanger":businessChanger]
        let company = ["CompanyCharger":companyCharger]
        let marketSupplyBase = ["ID": marketSupplyBaseID, "Company": company] as [String : Any]
        
        let migrantWorker = ["ID":migrantWorkerID]
        
        let form = ["MarketSupplyBase": marketSupplyBase, "MigrantWorker": migrantWorker, "OrderNo":orderNo, "IsApply": true] as [String : Any]
        
        let jsonData = ["ID":guid, "Form":form] as [String : Any]
        let jsonDataString = getJSONStringFromDictionary(dictionary: jsonData as NSDictionary)
        
        let params = ["Method": method, "pageName":pageName, "orderConfigId": orderConfigId, "orderId":guid, "jsonData": jsonDataString, "approvalNote":approvalNote, "carbonList":carbonList, "AccountId":accountId]
        Alamofire.request(API_CALL_METHOD, method: .post, parameters: params, headers: httpHeader).responseString { (response) in
            if response.result.isSuccess {
                if let valueString = response.result.value {
                    if valueString == "OK" {
                        completionHandler(WWResponse.init(success: true))
                    }
                    else {
                        completionHandler(WWResponse.init(success: false, message: valueString))
                    }
                    return
                }
                completionHandler(WWResponse.init(success: false, message: "数据解析错误"))
            }
            else {
                print("网络访问失败")
                completionHandler(WWResponse.init(success: false, message: "网络访问失败"))
            }
        }
    }
}

//struct StatusStruct {
//    var success: Bool = false
//    var statusString: String?
//
//    enum Status: String {
//        case okStatus = "OK"
//        case other
//    }
//
//    init(rootJson: [String: AnyObject]) {
//        guard let aStatus = rootJson["Status"] as? String else {
//            return
//        }
//        let status = Status(rawValue: aStatus)
//        if status == .okStatus {
//            self.success = true
//
//        }
//        self.statusString = aStatus
//    }
//}
//
struct LCStateStruct {
    var success: Bool = false
    var statusString: String?
    
    enum Status: String {
        case okStatus = "OK"
        case other
    }
    
    init(rootJson: [String: AnyObject]) {
        guard let aStatus = rootJson["State"] as? String else {
            return
        }
        let status = Status(rawValue: aStatus)
        if status == .okStatus {
            self.success = true
            
        }
        self.statusString = aStatus
    }
}





























